<template>
  <div class="course-video">
    <el-card>
      <div slot="header">
        上传视频
      </div>
      <el-form label-width="100px">
        <el-form-item label="课程">
          <span>{{ courseName }}</span>
        </el-form-item>
        <el-form-item label="课时">
          <span>{{ lessonName }}</span>
        </el-form-item>
        <el-form-item label="视频上传">
          <input ref="video-file" type="file" />
        </el-form-item>
        <el-form-item label="封面上传">
          <input ref="image-file" type="file" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpload">开始上传</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </el-form-item>
        <el-form-item>
          <p>视频上传中：{{ uploadPercent }}%</p>
          <p v-if="isUpoloadSuccess">
            视频转码中：{{ isTransCodeSuccess ? '完成' : '正在处理，请稍后' }}
          </p>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script lang="ts">
/* eslint-disable */
import Vue from 'vue'
import {
  getUliyunImagUploadAddressAdnAuth,
  getUliyunVideoUploadAddressAdnAuth,
  transCodeVideo,
  getAliyunTransCodePercent
} from '@/services/aliyun-upload'

export default Vue.extend({
  name: 'CourseVideo',
  props: {
    courseId: {
      type: [String, Number],
      required: true
    }
  },
  data() {
    return {
      courseName: '',
      lessonName: '',
      uploader: null,
      videoId: null,
      imageUrl: '',
      uploadPercent: 0,
      isUpoloadSuccess: false,
      isTransCodeSuccess: false
    }
  },
  // computed: {
  //   video() {
  //     return this.$refs['video-file']
  //   },
  //   image() {
  //     return this.$refs['image-file']
  //   }
  // },
  created() {
    this.courseName = decodeURIComponent((this.$route.query as any).courseName)
    this.lessonName = decodeURIComponent((this.$route.query as any).lessonName)
    this.initUploader()
  },
  methods: {
    initUploader() {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值
        userId: '1618139964448548',
        // 上传到视频点播的地域，默认值为'cn-shanghai'，//eu-central-1，ap-southeast-1
        region: '',
        // 分片大小默认1 MB，不能小于100 KB
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async (uploadInfo: any) => {
          console.log('onUploadstarted', uploadInfo)
          // 1、通过我们的后端获取文件上传凭证
          let uploadAuthInfo = null
          if (uploadInfo.isImage) {
            // 获取图片上传凭证
            const { data } = await getUliyunImagUploadAddressAdnAuth()
            this.imageUrl = data.data.imageURL
            uploadAuthInfo = data.data
          } else {
            // 获取视频上传凭证
            const { data } = await getUliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageUrl
            })
            this.videoId = data.data.videoId
            uploadAuthInfo = data.data
          }
          // 2、调用uploader.setUploadAuthAndAddress设置上传凭证
          ;(this.uploader as any).setUploadAuthAndAddress(
            uploadInfo,
            uploadAuthInfo.uploadAuth,
            uploadAuthInfo.uploadAddress,
            uploadAuthInfo.imageId || uploadAuthInfo.videoId
          )
          // 3、设置好上传凭证确认没有问题，上传进度开始
        },
        // 文件上传成功
        onUploadSucceed: function(uploadInfo: any) {
          console.log('onUploadSucceed', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function(uploadInfo: any, code: any, message: any) {
          console.log('onUploadFailed', uploadInfo, code, message)
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (
          uploadInfo: any,
          totalSize: any,
          loadedPercent: any
        ) => {
          console.log('onUploadProgress', uploadInfo, totalSize, loadedPercent)
          if (!uploadInfo.isImage) {
            this.uploadPercent = Math.floor(loadedPercent * 100)
          }
        },
        // 上传凭证或STS token超时
        onUploadTokenExpired: function(uploadInfo: any) {
          console.log('onUploadTokenExpired', uploadInfo)
        },
        // 全部文件上传结束
        onUploadEnd: async (uploadInfo: any) => {
          this.isUpoloadSuccess = true
          // 请求转码
          const { data } = await transCodeVideo({
            lessonId: (this.$route.query as any).lessonId,
            coverImageUrl: this.imageUrl,
            fileName: (this.$refs['video-file'] as any).files[0].name,
            fileId: this.videoId
          })
          console.log(data)

          // 轮询查询转码进度
          const timer = setInterval(async () => {
            const { data } = await getAliyunTransCodePercent(
              (this.$route.query as any).lessonId
            )
            this.isTransCodeSuccess = true
            console.log(data.data)
            if (data.data === 100) {
              window.clearInterval(timer)
              console.log('转码成功')
            }
          }, 3000)
        }
      })
    },
    handleUpload() {
      this.isUpoloadSuccess = false
      this.isTransCodeSuccess = false
      this.uploadPercent = 0
      // 获取上传的文件
      const videoFile = (this.$refs['video-file'] as any).files[0]
      const imageFile = (this.$refs['video-file'] as any).files[0]
        // 将用户所选的文件添加到上传列表中
        // 一旦开始上传，它就会按照列表中添加的顺序开始上传
      ;(this.uploader as any).addFile(imageFile, null, null, null, '{"Vod":{}}')
      ;(this.uploader as any).addFile(videoFile, null, null, null, '{"Vod":{}}')
      // 开始上传，触发onUploadstarted
      ;(this.uploader as any).startUpload()
    }
  }
})
</script>

<style lang="scss" scoped></style>
